package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.dao.PurchaseDetailDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.Item;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDetailService purchaseDetailService;
    @Resource
    private PurchaseDetailDao purchaseDetailDao;
    @Resource
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils unReceiveList(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PurchaseEntity::getStatus,0).or().eq(PurchaseEntity::getStatus,1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void merge(MergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        if(purchaseId==null){
            PurchaseEntity entity = new PurchaseEntity();
            entity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            this.save(entity);
            purchaseId = entity.getId();
        }
        List<Long> items = vo.getItems();
        //判断当前合并的订单状态是否合规
        List<PurchaseDetailEntity> detailEntities = purchaseDetailDao.selectBatchIds(items);
        List<PurchaseDetailEntity> collect1 = detailEntities.stream().filter(i -> {
            return i.getStatus() == WareConstant.PurchaseDetailEnum.CREATED.getCode() || i.getStatus() == WareConstant.PurchaseDetailEnum.ASSIGNED.getCode();
        }).collect(Collectors.toList());

        if(collect1.size()>0){
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = collect1.stream().map(i -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(i.getId());
                detailEntity.setPurchaseId(finalPurchaseId);
                detailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void received(List<Long> ids) {
        //1.确认当前采购单是 新建或者已分配
        List<PurchaseEntity> entities = this.baseMapper.selectBatchIds(ids);
        List<PurchaseEntity> collect = entities.stream().filter(i -> {
            return i.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || i.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2.改变采购单的状态
        this.updateBatchById(collect);

        //3.改变采购项的状态
        List<Long> purchaseIds = collect.stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        List<PurchaseDetailEntity> detailEntities = purchaseDetailDao.selectList(new LambdaQueryWrapper<PurchaseDetailEntity>().in(PurchaseDetailEntity::getPurchaseId,purchaseIds));
        List<PurchaseDetailEntity> list = detailEntities.stream().map(item -> {
            item.setStatus(WareConstant.PurchaseDetailEnum.BUYING.getCode());
            return item;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(list);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void done(PurchaseDoneVo vo) {
        //1.改变采购项的状态
        List<Item> items = vo.getItems();

        //利用flag 判断此次采购是否全部采购成功
        final int[] flag = {0};
        List<PurchaseDetailEntity> collect = items.stream().map(i->{
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(i.getItemId());
            detailEntity.setStatus(i.getStatus());
            flag[0] += i.getStatus()==WareConstant.PurchaseDetailEnum.FINISH.getCode()?1:0;
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        //2.根据采购项状态 改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(vo.getId());
        purchaseEntity.setStatus(flag[0]==items.size()?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.ERROR.getCode());
        this.baseMapper.updateById(purchaseEntity);

        //3.将成功采购的进行入库
        List<Long> ids = collect.stream().filter(i -> {
            return i.getStatus() == WareConstant.PurchaseDetailEnum.FINISH.getCode();
        }).map(i->{
            return i.getId();
        }).collect(Collectors.toList());
        List<PurchaseDetailEntity> entities = purchaseDetailDao.selectBatchIds(ids);
        wareSkuService.addStock(entities);
    }

}